package classify

import (
	"fmt"
	classifyDto "news_for_deepseek_interface/dto/admin/classify"
	"news_for_deepseek_interface/model"
)

func List(params classifyDto.ListRequest, types string) (response classifyDto.ListResponse, err error) {
	db := model.GetInstance().GetDB()

	if params.Title != nil {
		db = db.Where("title LIKE ?", "%"+*params.Title+"%")
	}

	if params.Type != nil {
		db = db.Where("type LIKE ?", "%"+*params.Type+"%")
	}

	db = db.Where("type = ?", types)

	// 获取总数
	var total int64
	if err = db.Model(&model.ClassifyModel{}).Count(&total).Error; err != nil {
		err = fmt.Errorf("数量查询失败%s", err.Error())
		return
	}

	// 分页查询
	offset := (params.Page - 1) * params.Limit
	var data []model.ClassifyModel
	if err = db.Model(&model.ClassifyModel{}).
		Offset(offset).
		Limit(params.Limit).
		Order("created_at DESC").
		Find(&data).Error; err != nil {
		err = fmt.Errorf("数据查询失败%s", err.Error())
		return
	}

	// 构建响应
	response = classifyDto.ListResponse{
		List:  make([]classifyDto.Classify, 0),
		Total: total,
		Page:  params.Page,
		Limit: params.Limit,
	}

	for _, v := range data {
		response.List = append(response.List, classifyDto.Classify{
			Id:        v.Id,
			Title:     v.Title,
			ParentId:  v.ParentId,
			Type:      v.Type,
			CreatedAt: v.CreatedAt.Format("2006-01-02 15:04"),
		})
	}

	return
}
